<template>
  <div id="whole">
    <!-- {{this.mk_title}} -->
    <!-- {{this.geoWK}} -->
    <!-- {{this.soilWK}} -->
    <!-- {{this.$refs.pop_box}} -->
    <div id="container" style="width: 100%; height: 100%; position: relative" >
        <el-tooltip placement="bottom" content="切换图层">
            <div class="change_layers" @click="mk_title_choice_show=mk_title_choice_show?false:true" >
                <div style="height: 45px; width: 45px;align-content:center;text-align:center;">
                    <img src="../../public/change_layers.png" style="height:35px;">
                </div>
            </div>
        </el-tooltip>
        <div style="position:absolute;z-index:10;top:20%;right:2%; background-color: pink;" v-show="mk_title_choice_show">
            <div class="title_choice"><el-radio v-model="mk_title" label="ALL" style="margin-left:10px">所有专题</el-radio></div>
            <div class="title_choice"><el-radio v-model="mk_title" label="地质专题" style="margin-left:10px">地质专题</el-radio></div>
            <div class="title_choice"><el-radio v-model="mk_title" label="土壤专题" style="margin-left:10px">土壤专题</el-radio></div>
            <div class="title_choice"><el-radio v-model="mk_title" label="生物专题" style="margin-left:10px">生物专题</el-radio></div>
        </div>
        <div ref="pop_box" style="display:flex;flex-direction:column;;position:absolute;z-index:10;background-color:white;width:360px;height:320px;">
            <div style="background-color:white;flex:0 0 10%;align-content:center;position:relative;">
                <i class="el-icon-info" style="margin-left:5px;margin-right:5px;border-bottom:1px solid black"></i>
                <span style="font-weight:bold;">{{box_data.title}}-采样点信息</span>
                <i class="el-icon-close" style="position:absolute;right:5%;" @click="overlay.setPosition(undefined)"></i>
            </div>
            <div style="flex:1;display:flex;box-shadow: 5px 5px 15px rgba(0, 0, 0.5);">
                <el-descriptions :column="1" border style="padding:5px;border-radius: 8px">
                    <el-descriptions-item>
                    <template slot="label">
                        样点编号
                    </template>
                        {{box_data.id_sample}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                    <template slot="label">
                        区县：
                    </template>
                        {{box_data.county}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                    <template slot="label">
                        乡镇：
                    </template>
                        {{box_data.town}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                    <template slot="label">
                        经度：
                    </template>
                        {{box_data.latitude}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                    <template slot="label">
                        纬度：
                    </template>
                        {{box_data.longitude}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                    <template slot="label">
                        时间：
                    </template>
                        {{box_data.time}}
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </div>
    </div>
  </div>
</template>

<script type="text/javascript" src='//webapi.amap.com/maps?v=2.0&key=8b9c8c5786f7ee7871906d9700229056'></script>
<script src="//webapi.amap.com/ui/1.1/main.js?v=1.1.1"></script>

<script>
import Axios from '@/my_axios';

import {Feature, Map, View} from 'ol';
import {fromLonLat, toLonLat} from 'ol/proj';
import {toStringHDMS} from 'ol/coordinate.js';

import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector'


import XYZ from 'ol/source/XYZ';
import VectorSource from 'ol/source/Vector';

import GeoJSON from 'ol/format/GeoJSON';
import {Style, Fill, Stroke, Circle, Icon} from 'ol/style';

import Point from 'ol/geom/Point';
import Overlay from 'ol/Overlay';


export default {
    name: "mapVue",
    async mounted() {
        this.initAMap();
        await this.getGeologyWK();
        await this.getSoilWK();
        await this.getZoologyWK();
        this.initMaket();
    },
    unmounted() {
        this.map?.destroy();
    },
    data: function () {
        return {
            id_tst: 234,
            AMap: null,
            map: null,
            geocoder: null,
            select_one: null,

            // mk_title
            mk_title:'ALL',
            mk_title_choice_show:false,

            // layers
            qxLayer:null,
            dzLayer:null,

            //fetch_statistic
            geoWK:null,
            soilWK:null,
            zoologyWK:null,

            box_data: {},
        };
    },
    watch: {
        mk_title(newCount) {
            // console.log('newOne:', newCount)
            // console.log(this.map.getLayers())
            if(newCount == "ALL"){
                this.map.getLayers().forEach(element=>{
                    element.setVisible(true);
                })
            }else if(newCount == "土壤专题") {
                this.map.getLayers().forEach(element=>{
                    if(element.get('name')=="turang")
                        element.setVisible(true);
                    if(element.get('name')=='dizi')
                        element.setVisible(false);
                    if(element.get('name')=='zoology')
                        element.setVisible(false);
                })
            }else if(newCount == "地质专题") {
                this.map.getLayers().forEach(element=>{
                    if(element.get('name')=="dizi")
                        element.setVisible(true);
                    if(element.get('name')=='turang')
                        element.setVisible(false);
                    if(element.get('name')=='zoology')
                        element.setVisible(false);
                    // element.setVisible(false);
                })
            }else if(newCount == "生物专题"){
                this.map.getLayers().forEach(element=>{
                    if(element.get('name')=='zoology')
                        element.setVisible(true);
                    if(element.get('name')=="dizi")
                        element.setVisible(false);
                    if(element.get('name')=='turang')
                        element.setVisible(false);
                    // element.setVisible(false);
                })
            }
        }
    },
    methods: {
        initAMap() {
            var tianditu_token = '816cded7027c0dd4de266ef32a030a19'
            this.map = new Map({
                target: 'container',
                view: new View({
                    projection: 'EPSG:3857',
                    center: fromLonLat([109, 30]),
                    // center: fromLonLat([0, 0]),
                    zoom: 8.3,
                }),
            });
            this.yxLayer = new TileLayer({
                name: 'tianditu_yx',
                zIndex:1,
                source: new XYZ({
                    url: "http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + tianditu_token,
                    wrapX: false
                })
            }),
            this.map.addLayer(this.yxLayer);

            this.yxmLayer = new TileLayer({
                name: 'tianditu_yxm',
                zIndex:3,
                source: new XYZ({
                    url: "http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" + tianditu_token,
                    wrapX: false
                })
            }),
            this.map.addLayer(this.yxmLayer);

            this.qxLayer = new VectorLayer({
                name: 'qx',
                zIndex:2,
                source: new VectorSource({
                    url: '/geoDatas/qx.json',
                    format: new GeoJSON(),
                }),
                style: this.getDefaultStyle,
            });
            this.map.addLayer(this.qxLayer);


            this.dzLayer = new VectorLayer({
                name:'dizi',
                zIndex:5,
                source: new VectorSource()
            });
            this.map.addLayer(this.dzLayer);

            this.trLayer = new VectorLayer({
                name:'turang',
                zIndex:5,
                source: new VectorSource()
            });
            this.map.addLayer(this.trLayer);
            this.zoologyLayer = new VectorLayer({
                name:'zoology',
                zIndex:5,
                source: new VectorSource()
            });
            this.map.addLayer(this.zoologyLayer);
            // for dialog
            this.overlay = new Overlay({
                name:'mark',
                zIndex:9,
                element: this.$refs.pop_box,
                positioning: 'bottom-center',
                stopEvent: false,
            });

            this.map.addOverlay(this.overlay);

            this.map.on('click', (e)=> {
                // console.log("点击事件：", e.coordinate)
                const feature = this.map.forEachFeatureAtPixel(e.pixel, (feature)=> {
                    return feature;
                })
                if(feature && feature.getGeometry() instanceof Point) {
                    // console.log("点击了:", feature.getKeys());
                    // console.log("点击了:", feature.get('index'), feature);//tmd, 必须为get才能取到; 然后就可以用this.GeoWK来取得对应WK的详细数据

                    let index = feature.get('index');
                    let title = feature.get('title');
                    if(title==="dz"){
                        this.box_data = this.geoWK[index];
                        this.box_data.title = "地质专题";
                    }else if(title==="tr"){
                        this.box_data = this.soilWK[index];
                        this.box_data.title = "土壤专题";
                    }else if(title=="zoology"){
                        this.box_data = this.zoologyWK[index];
                        this.box_data.title = "生物专题";
                    }
                    // console.log('box_data.latitude:',this.box_data.latitude)
                    this.overlay.setPosition(e.coordinate);
                }
            })

        },

        // 其他方法
        test() {
            console.log("*****test********");

            console.log("ssss:", [106.461, 29.6172]);
            // this.addMarker(this.dzLayer.getSource(), [106.461, 29.6172], "hehehehe")
            this.overlay.setPosition(undefined)
            // this.addMarker()
        },
        getDefaultStyle(feature){
            const name = feature.get('NAME99');

            const isHightlighted = (name === this.select_one);
            // console.log('--------------------------------', isHightlighted)
            return new Style({
                fill: new Fill({
                    color: isHightlighted? 'rgba(255, 0, 0, 0.6)' : 'rgba(58, 175, 205, 0.8)'
                }),
                stroke: new Stroke({
                    color: 'black',
                    width: 1
                })
            })
        },
        // 传入位置（地理坐标or城市编号），然后将当前地图中心聚焦于此地并设置合适的缩放比例
        focus_on(location, done) {
            // console.log('!!!!!!!!!!!!!', location)
            var view = this.map.getView()
            location = fromLonLat(location)
            // tmp.setCenter(fromLonLat(center));
            // https://openlayers.org/en/latest/examples/animation.html
            const duration = 2000;
            const zoom = view.getZoom();
            let parts = 2;
            let called = false;
            function callback(complete) {
                --parts;
                if (called) {
                return;
                }
                if (parts === 0 || !complete) {
                called = true;
                done(complete);
                }
            }
            view.animate(
                {
                center: location,
                duration: duration,
                },
                callback,
            );
            view.animate(
                {
                zoom: zoom - 1,
                duration: duration / 2,
                },
                {
                zoom: zoom,
                duration: duration / 2,
                },
                callback,
            );
        },
        navi_click(data) {
            this.select_one = data.label;
            this.qxLayer.setStyle(this.getDefaultStyle);
            //focus_on
            this.focus_on(data.lng, function(){})
        },
        addMarker(source, latitude, longitude, name, index, title) {
            // console.log("......", name)
            const corordinate = fromLonLat([longitude,latitude]);
            const point = new Point(corordinate);

            const market = new Feature({
                geometry: point,
                name: name,
                index: index,
                title: title, //为了后面弹出框的信息能够 区分两者的数据来源
            });

            var tmp;
            if(title=="dz"){
                tmp = '/workpoint/tb_geology_workpoint/dtSample.png'
            }else if(title=="tr"){
                tmp = '/workpoint/tb_soil_workpoint/trSample.png'
            }else if(title=="zoology"){
                tmp = '/workpoint/tb_zoology_workpoint/swSample.png'
            }

            market.setStyle(
                new Style({
                    image: new Icon({
                        src: tmp,
                        scale: 0.8
                    }),
                })
            );

            source.addFeature(market);
        },
        async getGeologyWK() {
            await Axios.post('/get_dzworkpoints')
            .then((resp)=>{
                // console.log(resp.data.data)
                this.geoWK = resp.data.data
            }).catch((e)=>{
                console.log(e)
            })
        },
        async getSoilWK() {
            await Axios.post('/get_trworkpoints')
            .then((resp)=>{
                // console.log(resp.data.data)
                this.soilWK = resp.data.data
            }).catch((e)=>{
                console.log(e)
            })
        },
        async getZoologyWK() {
            await Axios.post('/get_zoologyworkpoints')
            .then((resp)=>{
                // console.log(resp.data.data)
                this.zoologyWK = resp.data.data
            }).catch((e)=>{
                console.log(e)
            })
        },
        initMaket() {
            this.geoWK.forEach((element, index) => {
                this.addMarker(this.dzLayer.getSource(), element.latitude, element.longitude,element.county, index, 'dz')//获取点击位置
            });
            this.soilWK.forEach((element, index) => {
                this.addMarker(this.trLayer.getSource(), element.latitude, element.longitude,element.county, index, 'tr')//获取点击位置
            });
            this.zoologyWK.forEach((element, index) => {
                this.addMarker(this.zoologyLayer.getSource(), element.latitude, element.longitude,element.county, index, 'zoology')//获取点击位置
            });
        },
    },
};
</script>

<style scoped>
.box_column {
    flex: 0 0 14%;
    /* border: 1px solid black; */
    align-content: center;
    text-align: center;
}
.title_choice {
    width:160px;
    height: 60px;
    margin:3px;
    background-color: green;
    align-content: center;
    /* color:white; */
    /* background-image: url('../../public/turang.jpeg'); */
}
.title_choice /deep/ .el-radio__label {
    color: white;
}

.change_layers {
    position: absolute;
    z-index: 10;
    top:10%;
    right:2%;
    background-color: white;
    border: 2px solid grey;
}

.change_layers:hover {
    background-color: orange;
}

::v-deep .el-descriptions {
    width:100%;
}
</style>
